package com.ym.student.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ym.student.system.entity.Student;
import com.ym.student.system.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/students")
@CrossOrigin(origins = "*") // 允许跨域访问
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @PostMapping
    @Transactional
    public ResponseEntity<?> createStudent(@RequestBody Student student) {
        try {
            student.setCreateTime(LocalDateTime.now());
            student.setUpdateTime(LocalDateTime.now());
            boolean success = studentService.save(student);

            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "学生信息创建成功" : "学生信息创建失败");
            response.put("data", success ? student : null);

            return ResponseEntity.status(success ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST)
                    .body(response);
        } catch (Exception e) {
            return buildErrorResponse(e, "创建学生信息失败");
        }
    }

    @DeleteMapping("/{studentNo}")
    @Transactional
    public ResponseEntity<?> deleteStudent(@PathVariable Integer studentNo) {
        try {
            boolean success = studentService.removeById(studentNo);

            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "学生信息删除成功" : "未找到该学生信息");

            return ResponseEntity.status(success ? HttpStatus.OK : HttpStatus.NOT_FOUND)
                    .body(response);
        } catch (Exception e) {
            return buildErrorResponse(e, "删除学生信息失败");
        }
    }

    @PutMapping("/{studentNo}")
    @Transactional
    public ResponseEntity<?> updateStudent(@PathVariable Integer studentNo,
                                           @RequestBody Student student) {
        try {
            student.setStudentNo(studentNo);
            student.setUpdateTime(LocalDateTime.now());
            boolean success = studentService.updateById(student);

            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "学生信息更新成功" : "未找到该学生信息");
            response.put("data", success ? studentService.getById(studentNo) : null);

            return ResponseEntity.status(success ? HttpStatus.OK : HttpStatus.NOT_FOUND)
                    .body(response);
        } catch (Exception e) {
            return buildErrorResponse(e, "更新学生信息失败");
        }
    }

    @GetMapping("/{studentNo}")
    public ResponseEntity<?> getStudent(@PathVariable Integer studentNo) {
        try {
            Student student = studentService.getById(studentNo);

            if (student == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of(
                                "success", false,
                                "message", "未找到该学生信息"
                        ));
            }

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", student
            ));
        } catch (Exception e) {
            return buildErrorResponse(e, "获取学生信息失败");
        }
    }

    @GetMapping
    public ResponseEntity<?> getAllStudents() {
        try {
            List<Student> students = studentService.list();
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", students,
                    "total", students.size()
            ));
        } catch (Exception e) {
            return buildErrorResponse(e, "获取学生列表失败");
        }
    }

    @GetMapping("/page")
    public ResponseEntity<?> getStudentsByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String gender) {
        try {
            Page<Student> page = new Page<>(current, size);
            LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();

            if (name != null && !name.isEmpty()) {
                queryWrapper.like(Student::getName, name);
            }
            if (gender != null && !gender.isEmpty()) {
                queryWrapper.eq(Student::getGender, gender);
            }

            studentService.page(page, queryWrapper);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", page.getRecords());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("total", page.getTotal());
            response.put("pages", page.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return buildErrorResponse(e, "分页查询失败");
        }
    }

    private ResponseEntity<Map<String, Object>> buildErrorResponse(Exception e, String message) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("success", false);
        errorResponse.put("message", message);
        errorResponse.put("error", e.getMessage());
        errorResponse.put("timestamp", LocalDateTime.now());

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorResponse);
    }
    // 在StudentController.java中添加以下方法
    @GetMapping("/count")
    public ResponseEntity<Map<String, Object>> getStudentCount() {
        try {
            int count = (int) studentService.count();
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "code", 200,
                    "message", "获取学生总数成功",
                    "data", Map.of("count", count)
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "success", false,
                            "code", 500,
                            "message", "获取学生总数失败",
                            "error", e.getMessage()
                    ));
        }
    }
}